package server.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hankcs.hanlp.HanLP;

import server.domain.Area;
import server.domain.Page;
import server.mapper.AreaMapper;

@Service 
public class AreaService {
	@Autowired
	private AreaMapper mapper;

	public void importExel(MultipartFile file) throws FileNotFoundException, IOException {
		long start = System.currentTimeMillis();
		// 解析文件，把每一行解析出来，封装到一个Area对象里面去
		
		// 打开文件
		Workbook wb = new HSSFWorkbook(file.getInputStream());
		
		List<Area> areas = new ArrayList<>();
		// 读取内容
		for (Sheet sheet : wb) {			// 遍历文档里面的每一个表格
	        for (Row row : sheet) {			// 遍历当前表格的每一行
	        	String areaCode = row.getCell(0).getStringCellValue();
	        	String province = row.getCell(1).getStringCellValue();
	        	String city = row.getCell(2).getStringCellValue();
	        	String district = row.getCell(3).getStringCellValue();
	        	String postCode = row.getCell(4).getStringCellValue();
	        	
	        	Area entity = new Area();
	        	entity.setCity(city);
	        	entity.setProvince(province);
	        	entity.setId(areaCode);
	        	entity.setDistrict(district);
	        	entity.setPostcode(postCode);

	        	// 设置城市编码（城市的拼音）
	        	entity.setCitycode(HanLP.convertToPinyinString(
	        			city.substring(0, city.length() - 1), "", true));
	        	
	        	// 设置城市的简码（省市区的拼音首字母）
	        	// entity.setShortcode();
	        	String p = province.substring(0, province.length() - 1);
	        	String c = city.substring(0, city.length() - 1);
	        	String d = district.substring(0, district.length() - 1);
	        	String shortCode = HanLP.convertToPinyinFirstCharString(p + c + d, "", true);
	        	entity.setShortcode(shortCode);
	        	
	        	areas.add(entity);
	        	
	        	// 批量插入，一次插入两百条
	        	if (areas.size() >= 200) {
	        		mapper.insertBatch(areas);
	        		
	        		areas.clear();
	        	}
	        	
	        }
	    }
		
		wb.close();
		
		long end = System.currentTimeMillis();
		
		System.out.println("耗时：" + (end - start) / 1000);
	}

	public Page<Area> findPage(Integer page, Integer size) {
		// 查总记录数
		int total = mapper.getCount();
		
		List<Area> areas = mapper.findPage((page - 1) * size, size);
		
		Page<Area> pageData = new Page<>();
		pageData.setTotal(total);
		pageData.setItems(areas);
		
		// 查当前页
		return pageData;
	}
}
